package com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.repository.entity.HddcB1GeologysvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.service.HddcB1GeologysvyprojecttableService;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.HddcGeologicalsvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.HddcGeologicalsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.entity.HddcGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.service.HddcGeologicalsvypointService;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.viewobjects.HddcGeologicalsvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.viewobjects.HddcGeologicalsvypointVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.repository.entity.HddcWorkregionEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author lihelei
 * @date 2020-11-27
 */
@Service
public class HddcGeologicalsvypointServiceImpl implements HddcGeologicalsvypointService {

	@Autowired
    private HddcGeologicalsvypointRepository hddcGeologicalsvypointRepository;
    @Autowired
    private HddcGeologicalsvypointNativeRepository hddcGeologicalsvypointNativeRepository;
    @Autowired
    private HddcB1GeologysvyprojecttableService hddcB1GeologysvyprojecttableService;

    @Override
    public JSONObject queryHddcGeologicalsvypoints(HddcGeologicalsvypointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeologicalsvypointEntity> hddcGeologicalsvypointPage = this.hddcGeologicalsvypointNativeRepository.queryHddcGeologicalsvypoints(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeologicalsvypointPage);
        return jsonObject;
    }


    @Override
    public HddcGeologicalsvypointEntity getHddcGeologicalsvypoint(String id) {
        HddcGeologicalsvypointEntity hddcGeologicalsvypoint = this.hddcGeologicalsvypointRepository.findById(id).orElse(null);
         return hddcGeologicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeologicalsvypointEntity saveHddcGeologicalsvypoint(HddcGeologicalsvypointEntity hddcGeologicalsvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeologicalsvypoint.setUuid(uuid);
        hddcGeologicalsvypoint.setQualityinspectionStatus("0");
        hddcGeologicalsvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeologicalsvypoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeologicalsvypoint.setIsValid("1");
        this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypoint);
        return hddcGeologicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeologicalsvypointEntity updateHddcGeologicalsvypoint(HddcGeologicalsvypointEntity hddcGeologicalsvypoint) {
        UpdateUtil.copyNullProperties(hddcGeologicalsvypointRepository.findByUuidAndIsValid(hddcGeologicalsvypoint.getUuid(), "1"), hddcGeologicalsvypoint);
        hddcGeologicalsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeologicalsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypoint);
        return hddcGeologicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeologicalsvypoints(List<String> ids) {
        List<HddcGeologicalsvypointEntity> hddcGeologicalsvypointList = this.hddcGeologicalsvypointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvypointList) && hddcGeologicalsvypointList.size() > 0) {
            for(HddcGeologicalsvypointEntity hddcGeologicalsvypoint : hddcGeologicalsvypointList) {
                hddcGeologicalsvypoint.setIsValid("0");
                hddcGeologicalsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvypoint.setUpdateTime(new Date());
                this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeologicalsvypointQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeologicalsvypointEntity> yhDisasterEntities = hddcGeologicalsvypointNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeologicalsvypointVO> list=new ArrayList<>();
        for (HddcGeologicalsvypointEntity entity:yhDisasterEntities) {
            HddcGeologicalsvypointVO yhDisasterVO=new HddcGeologicalsvypointVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地质调查观测点-点", "地质调查观测点-点", HddcGeologicalsvypointVO.class, "地质调查观测点-点.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeologicalsvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeologicalsvypointVO.class, params);
            List<HddcGeologicalsvypointVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeologicalsvypointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeologicalsvypointVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public HddcGeologicalsvypointEntity findbyId(String geologicalsvypointid) {
        return hddcGeologicalsvypointRepository.findbyId(geologicalsvypointid);
    }

    @Autowired
    SuperRepository superRepository;
    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcGeologicalsvypointEntity> listAll = hddcGeologicalsvypointRepository.findByAll();
        List<HddcGeologicalsvypointEntity> updateList = new ArrayList<>();
        for (HddcGeologicalsvypointEntity b2All: listAll) {
            String str="";
            if (StringUtils.isEmpty(b2All.getProjectid())) {
                str+= "【地质调查观测点】工程编号为空。";
            }else {
                HddcB1GeologysvyprojecttableEntity hddcB1GeologysvyprojecttableEntity = hddcB1GeologysvyprojecttableService.findbyId(b2All.getProjectid());
                if (hddcB1GeologysvyprojecttableEntity == null) {
                    str += "【地质调查观测点】表单中的工程编号与【地质调查工程表】中的工程编号不一致。";
                }else {
                    if (b2All.getCollectedsamplecount()==null){
                        str += "【地质调查观测点】采集样品总数为空。";
                    }else {
                        if (!(b2All.getCollectedsamplecount() == hddcB1GeologysvyprojecttableEntity.getCollectedsamplecount())) {
                            str += "【地质调查观测点】表单中的采集样品总数与【地质调查工程表】中的采集样品总数不一致。";
                        }
                    }
                }
            }
            if(str.isEmpty()){
                str +="【地质调查观测点】与【地质调查工程表】质检成功。";
                b2All.setQualityinspectionStatus("1");
            }else{
                b2All.setQualityinspectionStatus("2");
            }
            b2All.setQualityinspectionComments(null);
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                    b2All.setExtends2(null);
                    b2All.setExtends3(null);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                    b2All.setExtends3(null);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeologicalsvypointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeologicalsvypointEntity yhDisasterEntity = new HddcGeologicalsvypointEntity();
            HddcGeologicalsvypointVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeologicalsvypoint(yhDisasterEntity);
        }
    }
}


